package com.customization.api.uddi.cmd;


import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;

import com.engine.workflow.biz.FormFieldSetBiz;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;

import weaver.general.LabelUtil;
import weaver.general.Util;
import weaver.hrm.User;

import weaver.workflow.selectItem.SelectItemManager;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.*;

/**
 * @author liutaihong
 * @version 1.0.0
 * @ClassName GenWsdlCmd.java
 * @Description TODO
 * @createTime 2019-10-23 20:40:00
 */
public class GenerateWsdlCmd extends AbstractCommonCommand<Map<String,Object>> {

    private int formid = 0;


    public GenerateWsdlCmd(Map<String,Object> params, User user){
        this.params=params;
        this.user=user;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }


    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> map=new HashMap<>();

        String wfid= Util.null2String(params.get("wfid"));
        String activewfid = new WorkflowComInfo().getActiveversionid(wfid);
        activewfid=activewfid.equalsIgnoreCase("")? wfid:activewfid;
        String worklfowname=new WorkflowComInfo().getWorkflowname(activewfid);
        this.formid = Util.getIntValue(new WorkflowComInfo().getFormId(activewfid));

        String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        xml+="<wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:p1=\"http://soap.ic1ng.cn/ws\" xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" name=\"createRequest\" targetNamespace=\"http://soap.ic1ng.cn/ws\">";
        xml+="  <wsdl:documentation/>";
        xml+="  <wsp:UsingPolicy wsdl:required=\"true\"/>";
        xml+="  <wsdl:types>";
        xml+="    <xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://soap.ic1ng.cn/ws\" targetNamespace=\"http://soap.ic1ng.cn/ws\">";
        xml+="      <xsd:element name=\"createResp\" type=\"DT_createResp\"/>";
        xml+="      <xsd:element name=\"createReq\" type=\"DT_createReq\"/>";
        xml+="      <xsd:complexType name=\"DT_createReq\">";

        xml+="        <xsd:annotation>";
        xml+="          <xsd:appinfo>创建："+worklfowname+"</xsd:appinfo>";
        xml+="          <xsd:documentation>您的IP："+params.get("param_ip")+",请确认该IP在白名单内。</xsd:documentation>";
        xml+="        </xsd:annotation>";
        xml+="        <xsd:sequence>";
        xml+="          <xsd:element name=\"row\" minOccurs=\"0\" maxOccurs=\"unbounded\"  >";
        xml+="            <xsd:annotation>";
        xml+="            <xsd:documentation>单据数据</xsd:documentation>\";";
        xml+="            </xsd:annotation>";
        xml+="            <xsd:complexType>";
        xml+="              <xsd:sequence>";

        //异构系统发起的单据
        xml += "                <xsd:element name=\"KEY\" type=\"xsd:string\" minOccurs=\"0\">";
        xml += "                  <xsd:annotation>";
        xml += "                    <xsd:documentation>异构系统单据主键，OA系统不存储，响应时返回。</xsd:documentation>";
        xml += "                  </xsd:annotation>";
        xml += "                </xsd:element>";

        //流程创建人
        xml += "                <xsd:element name=\"CREATOR\" type=\"xsd:string\" minOccurs=\"0\">";
        xml += "                  <xsd:annotation>";
        xml += "                    <xsd:documentation>流程创建人</xsd:documentation>";
        xml += "                  </xsd:annotation>";
        xml += "                </xsd:element>";

        //流程标题
        xml += "                <xsd:element name=\"REQUESTNAME\" type=\"xsd:string\" minOccurs=\"0\">";
        xml += "                  <xsd:annotation>";
        xml += "                    <xsd:documentation>流程标题</xsd:documentation>";
        xml += "                  </xsd:annotation>";
        xml += "                </xsd:element>";


        //遍历主表字段 START
        xml += "        <xsd:element name=\"MAINDATA\">";
        xml += "                  <xsd:annotation>";
        xml += "                    <xsd:documentation>主表数据</xsd:documentation>";
        xml += "                  </xsd:annotation>";
        xml += "        <xsd:complexType>";
        xml += "        <xsd:sequence>";
        List<Map<String, Object>> mainfiled=this.getMainTableDatas();
        for (Map<String, Object> maiFiledMap : mainfiled) {
            xml += "                <xsd:element name=\""+maiFiledMap.get("fieldName")+"\" type=\"xsd:string\" minOccurs=\"0\">";
            xml += "                  <xsd:annotation>";
            xml += "                    <xsd:documentation>"+maiFiledMap.get("fieldLabelName")+"</xsd:documentation>";
            xml += "                  </xsd:annotation>";
            xml += "                </xsd:element>";
        }
        xml+="                    </xsd:sequence>";
        xml+="                  </xsd:complexType>";
        xml+="                </xsd:element>";
        //遍历主表END

        //遍历明细表Start
        xml += "        <xsd:element name=\"DETAILDATA\">";
        xml += "                  <xsd:annotation>";
        xml += "                    <xsd:documentation>明细表数据</xsd:documentation>";
        xml += "                  </xsd:annotation>";
        xml += "        <xsd:complexType>";
        xml += "        <xsd:sequence>";
        Map<String, Object>   dtFiledsInfo=this.getDetailTableDatas();
        Set<Map.Entry<String,Object>> es=dtFiledsInfo.entrySet();
        Iterator<Map.Entry<String,Object>> it=es.iterator();
        while(it.hasNext()) {
            Map.Entry<String, Object> en=it.next();
            String key=en.getKey();
            xml += "           <xsd:element name=\""+key+"\" minOccurs=\"0\">";
            xml += "                  <xsd:annotation>";
            xml += "                  </xsd:annotation>";
            xml += "                  <xsd:complexType>";
            xml += "                    <xsd:sequence>";
            xml += "           <xsd:element name=\"item\" minOccurs=\"0\" maxOccurs=\"unbounded\" >";///
            xml+="            <xsd:complexType>";
            xml += "            <xsd:sequence>";

            ArrayList<Map<String,Object>> dtfiledArray=(ArrayList<Map<String,Object>>)en.getValue();
            //遍历明细字段
            for (Map<String, Object> dtfiled : dtfiledArray) {
                xml += "                      <xsd:element name=\""+dtfiled.get("fieldName")+"\" type=\"xsd:string\" minOccurs=\"0\">";
                xml += "                        <xsd:annotation>";
                xml += "                            <xsd:documentation>"+dtfiled.get("fieldLabelName")+"</xsd:documentation>";
                xml += "                        </xsd:annotation>";
                xml += "                      </xsd:element>";
            }
            xml+="                    </xsd:sequence>";
            xml+="                  </xsd:complexType>";
            xml+="                </xsd:element>";
            xml+="                    </xsd:sequence>";
            xml+="                  </xsd:complexType>";
            xml+="                </xsd:element>";
        }
        xml+="                    </xsd:sequence>";
        xml+="                  </xsd:complexType>";
        xml+="                </xsd:element>";
        //遍历明细表END


        xml+="              </xsd:sequence>";
        xml+="            </xsd:complexType>";
        xml+="          </xsd:element>";
        xml+="        </xsd:sequence>";
        xml+="      </xsd:complexType>";

        //返回消息
        xml+="      <xsd:complexType name=\"DT_createResp\">";
        xml+="        <xsd:annotation>";
        xml+="          <xsd:appinfo></xsd:appinfo>";
        xml+="        </xsd:annotation>";
        xml+="        <xsd:sequence>";
        xml+="          <xsd:element name=\"row\" minOccurs=\"0\"  >";
        xml+="            <xsd:annotation>";
        xml+="              <xsd:appinfo>返回信息</xsd:appinfo>";
        xml+="            </xsd:annotation>";
        xml+="            <xsd:complexType>";
        xml+="              <xsd:sequence>";

        xml+="                <xsd:element name=\"KEY\" type=\"xsd:string\" minOccurs=\"0\">";
        xml+="                  <xsd:annotation>";
        xml+="                    <xsd:documentation>异构数据请求主键，OA系统不存储，响应时返回</xsd:documentation>";
        xml+="                  </xsd:annotation>";
        xml+="                </xsd:element>";

        xml+="                <xsd:element name=\"REQUESTID\" type=\"xsd:string\" minOccurs=\"0\">";
        xml+="                  <xsd:annotation>";
        xml+="                    <xsd:documentation>流程主键，整个系统绝对唯一(推荐使用)，返回值大于0时，流程创建成功；返回值小于0时，流程创建失败，失败原因参考消息。</xsd:documentation>";
        xml+="                  </xsd:annotation>";
        xml+="                </xsd:element>";

        xml+="                <xsd:element name=\"REQUESTMARK\" type=\"xsd:string\" minOccurs=\"0\">";
        xml+="                  <xsd:annotation>";
        xml+="                    <xsd:documentation>流程编号，同路径下相对唯一（不推荐使用）</xsd:documentation>";
        xml+="                  </xsd:annotation>";
        xml+="                </xsd:element>";

        xml+="                <xsd:element name=\"STATUS\" type=\"xsd:string\" minOccurs=\"0\">";
        xml+="                  <xsd:annotation>";
        xml+="                    <xsd:documentation>状态 E 流程创建失败，S 流程创建成功</xsd:documentation>";
        xml+="                  </xsd:annotation>";
        xml+="                </xsd:element>";

        xml+="                <xsd:element name=\"MASSAGE\" type=\"xsd:string\" minOccurs=\"0\">";
        xml+="                  <xsd:annotation>";
        xml+="                    <xsd:documentation>消息</xsd:documentation>";
        xml+="                  </xsd:annotation>";
        xml+="                </xsd:element>";



        xml+="              </xsd:sequence>";
        xml+="            </xsd:complexType>";
        xml+="          </xsd:element>";
        xml+="        </xsd:sequence>";
        xml+="      </xsd:complexType>";
        xml+="    </xsd:schema>";
        xml+="  </wsdl:types>";


        xml+="  <wsdl:message name=\"createReq\">";
        xml+="    <wsdl:documentation/>";
        xml+="    <wsdl:part name=\"createReq\" element=\"p1:createReq\"/>";
        xml+="  </wsdl:message>";


        xml+="  <wsdl:message name=\"createResp\">";
        xml+="    <wsdl:documentation/>";
        xml+="    <wsdl:part name=\"createResp\" element=\"p1:createResp\"/>";
        xml+="  </wsdl:message>";



        xml+="  <wsdl:portType name=\"createRequest\">";
        xml+="    <wsdl:documentation/>";
        xml+="    <wsdl:operation name=\"createRequest\">";
        xml+="      <wsdl:documentation/>";
        xml+="      <wsdl:input message=\"p1:createReq\"/>";
        xml+="      <wsdl:output message=\"p1:createResp\"/>";
        xml+="    </wsdl:operation>";
        xml+="  </wsdl:portType>";


        xml+="  <wsdl:binding name=\"WorkflowServiceBinding\" type=\"p1:createRequest\">";
        xml+="    <wsdlsoap:binding xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"></wsdlsoap:binding>";
        xml+="    <wsdl:operation name=\"createRequest\">";
        xml+="      <wsdlsoap:operation xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" soapAction=\"http://ic1ng.cn/xi/WebService/soap1.1\"></wsdlsoap:operation>";
        xml+="      <wsdl:input>";
        xml+="        <wsdlsoap:body xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" use=\"literal\"></wsdlsoap:body>";
        xml+="      </wsdl:input>";
        xml+="      <wsdl:output>";
        xml+="        <wsdlsoap:body xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" use=\"literal\"></wsdlsoap:body>";
        xml+="      </wsdl:output>";
        xml+="    </wsdl:operation>";
        xml+="  </wsdl:binding>";
        //
        xml+="  <wsdl:service name=\"WorkflowService\">";
        xml+="    <wsdl:port name=\"HTTP_Port\" binding=\"p1:WorkflowServiceBinding\">";
        xml+="      <wsdlsoap:address xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" location=\"http://"+params.get("serverName")+"/api/custom/webservice/createReq?wfid="+wfid+"\"></wsdlsoap:address>";
        xml+="    </wsdl:port>";
        xml+="    <wsdl:port name=\"HTTPS_Port\" binding=\"p1:WorkflowServiceBinding\">";
        xml+="      <wsdlsoap:address xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" location=\"https://"+params.get("serverName")+"/api/custom/webservice/createReq?wfid="+wfid+"\"></wsdlsoap:address>";
        xml+="    </wsdl:port>";
        xml+="  </wsdl:service>";
        //
        xml+="</wsdl:definitions>";
        map.put("result",xml);
        return map;
    }

    protected List<Map<String, Object>> getMainTableDatas() {
        ArrayList arrayList = new ArrayList();
        RecordSet rs = new RecordSet();
        String sql = "select t.*,(select 1 from workflow_billfield chit where chit.id = t.childfieldid and chit.fieldhtmltype = 5 and chit.selectitemtype = 2) as existschild from workflow_billfield t where billid=" + this.formid + " and viewtype=0 order by dsporder,id";
        rs.executeQuery(sql);
        for(int i = 0; rs.next(); ++i) {
            HashMap mainfiled = new HashMap();
            String id = rs.getString("id");
            String fieldname   = rs.getString("fieldname");

            mainfiled.put("fieldId", id);
            mainfiled.put("fieldName", Util.toScreen(fieldname, this.user.getLanguage()).toUpperCase());
            mainfiled.put("fieldLabelName", LabelUtil.getMultiLangLabel(rs.getString("fieldlabel")));
            FormFieldSetBiz formFieldSetBiz = new FormFieldSetBiz(this.formid, 1, this.user, false);
            List fieldType = formFieldSetBiz.getFieldTypeData(this.formid, Util.getIntValue(id), true);
            mainfiled.put("fieldType", fieldType);
            arrayList.add(mainfiled);
        }

        return arrayList;
    }

    protected Map<String, Object> getDetailTableDatas() {
        Map<String, Object> map=new LinkedHashMap<>();
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        recordSet.executeQuery("select * from Workflow_billdetailtable where billid=" + this.formid + " order by orderid");
        while(recordSet.next()) {
            String formname=recordSet.getString("tablename").toUpperCase();

            ArrayList<Map<String,Object>> dtinfo = new ArrayList<Map<String,Object>>();
            rs.executeQuery("select t.*,(select 1 from workflow_billfield chit where chit.id = t.childfieldid and chit.fieldhtmltype = 5 and chit.selectitemtype = 2) as existschild from workflow_billfield t where billid=" + this.formid + " and viewtype=1 and detailtable='" + formname + "' order by dsporder,id", new Object[0]);
            while(rs.next()) {
                Map<String,Object> dtfiled = new HashMap();
                String fieldId = rs.getString("id");
                String  fieldname = rs.getString("fieldname");
                dtfiled.put("fieldId", fieldId);
                dtfiled.put("fieldName", Util.toScreen(fieldname, this.user.getLanguage()).toUpperCase());
                dtfiled.put("fieldLabelName", LabelUtil.getMultiLangLabel(rs.getString("fieldlabel")));
                FormFieldSetBiz formFieldSetBiz = new FormFieldSetBiz(this.formid, 1, this.user, true);
                List fieldType = formFieldSetBiz.getFieldTypeData(this.formid, Util.getIntValue(fieldId), true);
                dtfiled.put("fieldType", fieldType);
                dtinfo.add(dtfiled);
            }
            String dt="1";
            if(formname.contains("_dt")) dt=formname.substring(formname.lastIndexOf("_")+1);
            map.put(formname,dtinfo);
        }

        return map;
    }


    public void getfieldinfo() {
        this.formid = -3;
        System.out.println("主表:" + JSONArray.fromObject(this.getMainTableDatas()));
        System.out.println("明细表:" + JSONObject.fromObject(this.getDetailTableDatas()));
    }


}
